<template lang="html">
  <div>
    <Row>
      <Col span="18">
        <div :style="{backgroundColor: '#fff'}">
          <div class="blog" ref="document">
            <h2 class="blog-tilte">{{ blogInfo.title }}</h2>
            <div class="blog-author">
              作者：<span><a>{{blogInfo.authorName}}</a></span>
              <!-- blogInfo.authorId -->
              | 创建于：<span>{{$moment(blogInfo.createTime).format('YYYY/MM/DD HH:mm:ss')}}</span>

            </div>
            <!-- <div v-html="blogInfo.content"></div> -->

            <quill-editor v-model="blogInfo.content" :options="editorOpts">
            </quill-editor>
            <div class="blog-desc" v-if="blogInfo.description">备注：{{blogInfo.description}}</div>
          </div>
        </div>
        <div class="blog-comment-layout">
          <div v-if="loggedIn">
            <Form ref="blogComment" :model="blogComment" :rules="blogCommentRule">
             <FormItem prop="comment">
               <Input type="textarea" v-model="blogComment.comment" placeholder="添加评论..." :autosize="{minRows: 2,maxRows: 5}"></Input>
             </FormItem>
             <FormItem :style="{textAlign: 'right'}">
               <Button type="primary" @click="handleBlogComment">发送</Button>
             </FormItem>
           </Form>
          </div>
          <div v-else :style="{ lineHeight: '30px', fontSize: '14px', padding: '10px 0'}">
            登录后才能添加评论！
          </div>

          <!-- 历史评论区 -->
          <div v-cloak v-for="(comment, key) in targetBlogComments" class="blog-comment-pane">
            <div class="comment-layout">
              <Avatar v-if="comment.photoUrl" :src="comment.photoUrl" size="large" style="margin-right: 10px;" />
              <Avatar v-else size="large" style="margin-right: 10px;">
                {{ comment.username ? comment.username.substring(0, 1) : 'U' }}
              </Avatar>
              <div :style="{display: 'inline-block', verticalAlign: 'middle'}">
                <p class="comment-author">{{ comment.username }}</p>
                <p class="comment-time">{{ $moment(comment.commentTime).format('YYYY/MM/DD HH:mm:ss') }}</p>
              </div>
            </div>
            <div style="overflow: hidden">
              <div class="comment-content">{{comment.comment}}</div>
              <div class="comment-tool">
                  <Icon color="#666" type="android-textsms" size="18" class="comment-tool-icon"></Icon>
              </div>
            </div>

            <div class="comment-replies">
              <div v-for="(reply, replyKey) in comment.blogCommentReplies" class="comment-replies-pane">
                <div class="comment-reply-layout">
                  <a>{{reply.username}}</a>: <a>@ {{reply.replayUsername}} </a>
                  <span>{{reply.content}}</span>
                </div>
                <p class="comment-reply-time">
                  {{$moment(reply.createTime).format('YYYY/MM/DD HH:mm:ss')}}
                  <span @click="handleCommentReplyInput" :style="{cursor: 'pointer'}"><Icon color="#999" type="android-textsms" size="16" class="comment-reply-icon"></Icon> 回复</span>
                </p>

                <div :style="{display: 'none'}">
                  <Input value="" :ref="'commentReply' + key + 'reply' + replyKey" type="textarea" placeholder="添加回复..." :autosize="{minRows: 2,maxRows: 5}"></Input>
                  <p style="textAlign: right; marginTop: 10px;">
                    <Button type="primary" @click="handleCommentReply(comment._links.self.href, reply.userId, 'commentReply' + key + 'reply' + replyKey, $event)">回复</Button>
                  </p>
                </div>
              </div>

              <div>
                <p>
                  <span :style="{cursor: 'pointer'}" @click="handleCommentReplyInput">
                    <Icon size="12" type="edit" color="#666" :style="{verticalAlign: 'middle', marginRight: '5px', lineHeight: '30px'}"></Icon> 回复
                  </span>
                </p>
                <div :style="{display: 'none'}">
                  <Input value="" :ref="'commentReply' + key" type="textarea" placeholder="添加回复..." :autosize="{minRows: 2,maxRows: 5}"></Input>
                  <p style="textAlign: right; marginTop: 10px;">
                    <Button type="primary" @click="handleCommentReply(comment._links.self.href, comment.userId, 'commentReply' + key, $event)">回复</Button>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Col>
      <Col span="6" :style="{paddingLeft: '10px'}">
        <Card :style="{borderRadius: '0px', minHeight: '300px'}">
          <p slot="title"></p>
        </Card>
      </Col>
    </Row>
    <div class="blog-tools">
      <ButtonGroup vertical>
        <!-- <Tooltip content="分享到新浪微博" placement="left"> -->
          <Button type="ghost" icon="social-pinterest" @click="handleShare"></Button>
        <!-- </Tooltip> -->
        <!-- <Tooltip content="下载到本地" placement="left"> -->
          <Button type="ghost" icon="android-download" @click="handleDownload"></Button>
        <!-- </Tooltip> -->
          <Poptip placement="left" class="poptip-button-group">
            <Button type="ghost" icon="qr-scanner"></Button>
            <div slot="content">
              <canvas id="canvas" class="qrcode"></canvas>
            </div>
          </Poptip>
      </ButtonGroup>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import FileSaver from 'filesaver.js'
import QRCode from 'qrcode'
export default {
  data() {
    return {
      blogId: this.$route.params.blogId,
      blogInfo: {
        title: '',
        content: '',
        description: '',
        uri: '',
        authorId: null,
        createTime: 0,
        authorName: '',
      },
      blogComment: {
        comment: '',
      },
      blogCommentRule: {
        comment: [
        ],
      },
      targetBlogComments: [],
      editorOpts: {
        readOnly: true,
        minHeight: 500,
        modules: {
          toolbar: null
        },
        theme: 'bubble'
      },
    }
  },
  computed: {
    ...mapState(['loggedIn'])
  },
  methods: {
    ...mapActions(['getUsernameById', 'getUsernameAndPhotoUrlById', 'queryIPAddr', 'viewBlogAsync']),
    handleBlogDetail () {
      this.$store.dispatch('blogDetailAsync', this.blogId)
        .then(async res => {
          this.blogInfo = {
            title: res.data.title,
            content: res.data.content,
            description: res.data.description,
            uri: res.data._links.self.href,
            authorId: res.data.authorId,
            createTime: res.data.createTime,
            authorName: await this.getUsernameById(res.data.authorId)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 发表评论
    handleBlogComment () {
      this.$refs.blogComment.validate((valid) => {
        if (valid) {
          this.$store.dispatch('blogCommentAsync', {
            comment: this.blogComment.comment,
            blogUri: this.blogInfo.uri
          })
          .then(res => {
            console.log(res.data)
            this.blogComment.comment = ''
            this.handleBlogCommentList()
          })
          .catch(err => {
            console.log(err)
          })
        }
      })
    },
    // 获取本篇评论
    async handleBlogCommentList () {
      const res = await this.$store.dispatch('targetBlogCommentAsync', this.blogId)
      if(res.data) {
        this.targetBlogComments = res.data._embedded.blogComments
        this.targetBlogComments.map(async (comment, index) => {
          let {username, photoUrl} = await this.getUsernameAndPhotoUrlById(comment.userId)
          // Object.assign(comment, { username })
          this.$set(comment, 'username', username)
          this.$set(comment, 'photoUrl', photoUrl)
          if (comment.blogCommentReplies) {
            comment.blogCommentReplies.map(async reply => {
              let username = await this.getUsernameById(reply.userId)
              let replayUsername = await this.getUsernameById(reply.replayUserId)
              // Object.assign(reply, {username, replayUsername})
              this.$set(reply, 'username', username)
              this.$set(reply, 'replayUsername', replayUsername)
            })
          }
        })
      }
        // .catch(err => {
        //   console.log(err)
        //   this.$Message.error('获取评论出错')
        // })
    },

    // 回复功能
    handleCommentReply (commentUri, replayUserId, replyRef, event) {
      console.log(commentUri, this.$refs[replyRef][0].currentValue)
      this.$store.dispatch('replyBlogCommentAsync', {
        content: this.$refs[replyRef][0].currentValue,
        replayUserId,
        commentUri,
      })
      .then(res => {
        if (res.data) {
          console.log('回复成功');
          this.$refs[replyRef][0].currentValue = ''
          event.target.closest('button').parentNode.parentNode.style.display = 'none'
          // this.$refs[replyRef][0].parentNode.style.display = 'none'
          this.handleBlogCommentList()
        }
      })
    },

    // 通过评论Id获取回复
    handleRepliesByCommentId (commentId) {
      this.$store.dispatch('commentRepliesAsync', commentId)
        .then(res => {
          console.log(res.data)
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 显示/隐藏
    handleCommentReplyInput (event) {
      if (!this.loggedIn) {
        this.$Message.error('请先登录！')
        return
      }
      const target = event.target.closest('span').parentNode.nextElementSibling;
      if (target.style.display === 'none') {
        target.style.display = 'block'
      } else {
        target.style.display = 'none'
      }

    },

    // 下载
    handleDownload () {
      let nodes = this.$refs.document.cloneNode(true)
      // <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      let temp = `<!DOCTYPE html>
                  <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"
                    xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
                    xmlns="http://www.w3.org/TR/REC-html40">
                    <head>
                      <meta charset="utf-8">
                      <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="off"/><m:dispDef/><m:lMargin m:val="0"/> <m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:WordDocument></xml><![endif]-->
                    </head>
                    <body>${nodes.innerHTML}</body>
                  </html>
                  `
      let blob = new Blob([temp], {type: 'application/msword;charset=utf-8'})
      FileSaver.saveAs(blob, `${this.blogInfo.title ? this.blogInfo.title : new Date().getTime()}.doc`)
    },
    // 分享
    handleShare () {
      // const url = this.$router.
      const blogName = `<<${this.blogInfo.title}>>`
      window.location = "javascript:void((function(s,d,e,r,l,p,t,z,c){var%20f='http://v.t.sina.com.cn/share/share.php?appkey=1309733143',u=z||d.location,p=['&url=',e(u),'&title=',e(t||d.title),'&source=',e(r),'&sourceUrl=',e(l),'&content=',c||'gb2312','&pic=',e(p||'')].join('');function%20a(){if(!window.open([f,p].join(''),'mb',['toolbar=0,status=0,resizable=1,width=440,height=430,left=',(s.width-440)/2,',top=',(s.height-430)/2].join('')))u.href=[f,p].join('');};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else%20a();})(screen,document,encodeURIComponent,'','','http://sma2lbao.gitee.io/static/img/logo.png','#Sma2lBao#不着一字，尽得风流。"+ blogName +"','"+ window.location.href +"','gb2312'));"
    },
    handleQRCode () {
      QRCode.toCanvas(document.getElementById('canvas'), window.location.href, (err) => {
        if (err) {
          console.log(err)
        }
        console.log('success');
      })
    },
    async handleBlogView () {
      const ip = await this.queryIPAddr()
      this.viewBlogAsync({uri: this.blogInfo.uri, ip})
        .then(res => {
          console.log('访问量+1')
        })
        .catch(err => {
          console.error(err)
        })
    }
  },
  mounted () {
    this.handleBlogCommentList()
    this.handleBlogDetail()
    this.handleQRCode()
    this.handleBlogView()
  }
}
</script>

<style lang="css">
  .blog {
    padding: 20px 40px;
  }
  .blog-tilte {
    text-align: center;
    line-height: 40px;
    font-size: 30px;
    margin-bottom: 10px;
  }
  .blog-author {
    text-align: right;
    font-size: 12px;
    margin-bottom: 10px;
  }
  .blog-desc {
    margin-top: 10px;
    font-size: 12px;
    color: #999;
  }
  .blog-comment-layout {
    background-color: #fcfcfc;
    padding: 20px 40px;
  }
  .blog-comment-author {

  }
  .comment-layout {

  }
  .blog-comment-pane {
    border-top: 1px solid #ddd;
    padding: 20px 0;
  }
  .comment-author {
    font-weight: 400;
    font-size: 14px;
  }
  .comment-time {
    font-size: 12px;
    color: #999;
  }
  .comment-content {
    padding: 10px 0;
    line-height: 25px;
    font-size: 14px;
    width: calc(100% - 50px);
    float: left;
  }
  .comment-tool {
    width: 50px;
    float: left;
    text-align: center;
    line-height: 25px;
    padding: 10px 0;
  }
  .comment-tool-icon {
    cursor: pointer;
  }
  .comment-reply-layout {
    line-height: 25px;
    font-size: 14px;
  }
  .comment-replies {
    border-left: 2px solid #ddd;
    padding-left: 20px;
  }
  .comment-reply-time {
    color: #999;
    line-height: 25px;
  }
  .comment-reply-icon {
    vertical-align: middle;
    margin: 0 5px 0 15px;
  }
  .comment-replies-pane {
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px dashed #ddd;
  }
  .blog-tools {
    position: fixed;
    bottom: 60px;
    right: 40px;
  }
  .blog-tools button{
    background-color: #fff;
  }
  .qrcode {
    width: 120px !important;
    height: 120px !important;
  }
  .poptip-button-group {
    display: inline-block;
    width: 100%;
    height: 100%;
    margin-top: -1px;
  }
  .poptip-button-group .ivu-poptip-rel {
    display: block;
    width: 100%;
    height: 100%;
  }
  .poptip-button-group button{
    display: block;
    width: 100%;
    height: 100%;
    border-top-right-radius: 0;
    border-top-left-radius: 0;
  }
</style>
